package com.xxh.dasongapp.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xxh.dasongapp.common.Result;
import com.xxh.dasongapp.common.dto.UserDTO;
import com.xxh.dasongapp.common.entity.User;
import com.xxh.dasongapp.common.param.UserPARAM;
import com.xxh.dasongapp.common.param.common.PagePARAM;
import com.xxh.dasongapp.common.validgroup.Insert;
import com.xxh.dasongapp.common.validgroup.Update;
import com.xxh.dasongapp.common.vo.UserVo;
import com.xxh.dasongapp.controller.common.AbstractController;
import com.xxh.dasongapp.controller.common.BaseController;
import com.xxh.dasongapp.service.UserService;
import com.xxh.dasongapp.utils.EmptyToNullUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;

@RestController
@PreAuthorize("hasAuthority('ROLE_ADMIN')")
@RequestMapping(value = "/user")
@Api(tags = "用户模块接口")
@Slf4j
public class UserController  extends AbstractController<User,UserDTO,UserPARAM> {

    @Resource
    private UserService userService;



    @ApiOperation(value = "添加用户")
    @PostMapping(value = "/add")
    public Result<UserDTO> add(@RequestBody @Validated({Insert.class}) UserPARAM userPARAM){
        User user = paramToEntity(userPARAM);
        User oldUsername = userService.getByUsername(user.getUsername());
        Assert.isNull(oldUsername, "添加失败，用户名重复");
        userService.saveUserAndRole(user,userPARAM.getRoleId());
        //不将密文返回
        user.setPassword("");
        return Result.success(entityToDto(user));
    }


    @ApiOperation(value = "更新用户")
    @PutMapping(value = "/update")
    public Result<UserDTO> update(@RequestBody @Validated({Update.class}) UserPARAM userPARAM){
        User user = paramToEntity(userPARAM);
        userService.saveOrUpdateUserAndRole(user,userPARAM.getRoleId());
        //不将密文返回
        user.setPassword("");
        return Result.success(entityToDto(user));
    }

    @ApiOperation(value = "根据id删除用户")
    @DeleteMapping(value = "/delete/{id}")
    public Result<String> deleteById(@PathVariable String id) {
        userService.removeUserAndRoleById(id);
        return Result.success(id);
    }



    @ApiOperation(value = "根据id集合删除")
    @DeleteMapping(value = "/delete")
    public Result<List<String>> deleteByIds(@RequestBody List<String> ids) {
        return Result.error("接口已废除，删除失败",ids);
    }


    @ApiOperation(value = "根据id查询用户")
    @GetMapping(value = "/{id}")
    public Result<UserVo> getById(@PathVariable String id) {
        return Result.success(userService.getUserAndRoleById(id));
    }


    @ApiOperation(value = "分页查询")
    @PostMapping(value = "/page")
    public Result<?> getByPage(@RequestBody PagePARAM<UserPARAM> pagePARAM) throws IllegalAccessException {
        Page<UserVo> page = new Page<UserVo>(pagePARAM.getPageNum(),pagePARAM.getPageSize());


        QueryWrapper<UserVo> qw = new QueryWrapper<UserVo>();

        if (StringUtils.isNotBlank(pagePARAM.getOrderBy()) && StringUtils.isNotBlank(pagePARAM.getOrder())){
            if (pagePARAM.getOrder().equals("desc")){
                qw.orderByDesc(pagePARAM.getOrderBy());
            }
            if (pagePARAM.getOrder().equals("asc")){
                qw.orderByAsc(pagePARAM.getOrderBy());
            }
        }

        if (pagePARAM.getSearchPARAM()!=null){
            UserVo userVo = new UserVo();
            BeanUtils.copyProperties(pagePARAM.getSearchPARAM(),userVo);
            EmptyToNullUtils.setNullValue(userVo);

            if (StringUtils.isNotBlank(userVo.getName())){
                qw.like("u.name",userVo.getName());
            }
            if (StringUtils.isNotBlank(userVo.getUsername())){
                qw.like("u.username",userVo.getUsername());
            }

            if (StringUtils.isNotBlank(userVo.getId())){
                qw.like("u.id",userVo.getId());
            }
            if (StringUtils.isNotBlank(userVo.getCreateTime())){
                qw.like("u.create_time",userVo.getCreateTime());
            }
            if (userVo.getStatus()!=null){
                qw.eq("u.status",userVo.getStatus());
            }
            if (userVo.getRoleId()!=null){
                qw.eq("r.role_id",userVo.getRoleId());
            }


            return Result.success(this.userService.getUserAndRoleByPage(page,qw));
        }
        return Result.success(this.userService.getUserAndRoleByPage(page,qw));
    }


}
